package com.zhenyi.youqu.miniapp;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;

import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.youqu.common.model.YqApp;
import com.youqu.common.model.YqCart;
import com.youqu.common.model.YqGroup;
import com.youqu.common.model.YqItem;
import com.youqu.common.model.YqOrder;
import com.youqu.common.model.YqOrderCart;
import com.youqu.common.model.YqOrderInfo;
import com.youqu.common.model.YqPaidProduct;
import com.youqu.common.model.YqProduct;
import com.youqu.common.model.YqProductFormat;
import com.youqu.common.model.YqProductGroup;
import com.youqu.common.model.YqUser;
import com.youqu.common.model.YqUserOrderGroup;
import com.zhenyi.youqu.core.OrderHandler;
import com.zhenyi.youqu.core.YQMiniAppController;
import com.zhenyi.youqu.interceptor.YQUserInterceptor;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 订单相关
 * 
 * @author cen
 *
 */
public class OrderController extends YQMiniAppController {

	@Before({ YQUserInterceptor.class })
	public void list() {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		SqlPara sqlPara = db.getSqlPara("YQAllOrder", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (StrKit.notBlank(record.getStr("cartContent"))) {
				JSONArray array = JSONUtil.parseArray(record.getStr("cartContent"));
				record.set("cart", array);
			}
		}
		renderPage(pages);
	}

	/**
	 * 待支付
	 */
	@Before({ YQUserInterceptor.class })
	public void topay() {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		SqlPara sqlPara = db.getSqlPara("YQOrderToPay", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (StrKit.notBlank(record.getStr("cartContent"))) {
				JSONArray array = JSONUtil.parseArray(record.getStr("cartContent"));
				record.set("cart", array);
			}
		}
		renderPage(pages);
	}

	/**
	 * 已支付
	 */
	@Before({ YQUserInterceptor.class })
	public void paid() {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		SqlPara sqlPara = db.getSqlPara("YQOrderPaid", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (StrKit.notBlank(record.getStr("cartContent"))) {
				JSONArray array = JSONUtil.parseArray(record.getStr("cartContent"));
				record.set("cart", array);
			}
		}
		renderPage(pages);
	}

	/**
	 * 已购买商品(购物车环境)
	 */
	@Before({ YQUserInterceptor.class })
	public void paidProducts() {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = getSimpleKv("orderId", "status");
		kv.set("userId", userId);
		SqlPara sqlPara = db.getSqlPara("YQPaidProducts", kv);
		Page<YqPaidProduct> pages = YqPaidProduct.dao.paginate(getPage(), getPageSize(), sqlPara);
		renderPage(pages);
	}

	/**
	 * 已完成订单
	 * 
	 * @Time 2019年1月12日 下午1:08:56
	 */
	@Before({ YQUserInterceptor.class })
	public void complete() {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		SqlPara sqlPara = db.getSqlPara("YQOrderComplete", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (StrKit.notBlank(record.getStr("cartContent"))) {
				JSONArray array = JSONUtil.parseArray(record.getStr("cartContent"));
				record.set("cart", array);
			}
		}
		renderPage(pages);
	}

	/**
	 * 待发货
	 */
	@Before({ YQUserInterceptor.class })
	public void pending() {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		SqlPara sqlPara = db.getSqlPara("YQOrderPending", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		for (Record record : pages.getList()) {
			if (StrKit.notBlank(record.getStr("cartContent"))) {
				JSONArray array = JSONUtil.parseArray(record.getStr("cartContent"));
				record.set("cart", array);
			}
		}
		renderPage(pages);
	}

	private void getProductByType(int type) {
		YqUser user = getUser();
		Long userId = user.getId();
		Kv kv = Kv.by("userId", userId);
		if (type == 1) {
			kv.set("isProduct", 1);
		} else if (type == 2) {
			kv.set("isGroup", 1);
		} else if (type == 3) {
			kv.set("isCard", 1);
		} else {
			renderFailure();
			return;
		}
		SqlPara sqlPara = db.getSqlPara("YQOrderGroupCardProduct", kv);
		Page<Record> pages = db.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	/**
	 * 已购团购列表
	 */
	@Before({ YQUserInterceptor.class })
	public void groups() {
		getProductByType(2);
	}

	/**
	 * 已购卡券列表
	 */
	@Before({ YQUserInterceptor.class })
	public void cards() {
		getProductByType(3);
	}

	/**
	 * 已购商品列表
	 */
	@Before({ YQUserInterceptor.class })
	public void products() {
		getProductByType(1);
	}

	// /**
	// * 订单列表
	// */
	// @Override
	// public void list() {
	// }

	/**
	 * 退款
	 */
	@Before({ YQUserInterceptor.class })
	public void refund() {
		renderError(401);
	}

	/**
	 * 订单详情
	 */
	@Before({ YQUserInterceptor.class })
	@Override
	public void info() {
		Long orderId = getParaToLong("orderId");
		if (orderId == null) {
			renderFailure(500, "order id is null");
			return;
		}
		YqUser user = getUser();
		Kv kv = Kv.create();
		kv.set("orderId", orderId);
		kv.set("userId", user.getId());
		SqlPara sqlPara = db.getSqlPara("YQOrderInfo", kv);
		YqOrderInfo info = YqOrderInfo.dao.findFirst(sqlPara);
		if (info == null) {
			renderFailure(404, "未找到订单");
			return;
		}
		YqOrderCart orderCart = YqOrderCart.dao.findById(orderId);
		if (orderCart != null) {
			JSONArray array = JSONUtil.parseArray(orderCart.getContent());
			info.put("cart", array);
		}
		YqOrder order = YqOrder.dao.findById(orderId);
		info.put("map", order.getShopUserMap(""));
		renderResult(info);
	}

	/**
	 * 关闭订单
	 */
	@Before({ YQUserInterceptor.class })
	public void close() {
		Long orderId = getParaToLong("orderId");
		if (orderId == null) {
			LogKit.info("orderId null");
			renderError(404);
			return;
		}
		YqOrder order = YqOrder.dao.findById(orderId);
		if (order == null) {
			LogKit.info("order null");
			renderError(404);
			return;
		}
		order.closeOrder();
		renderSuccess();
	}

	/**
	 * 当前订单是否能支付(暂时停止直接重复支付功能)
	 * 
	 * @param order
	 * @return
	 */
	private boolean canPay(YqOrder order) {
		order.updateOrderStatus();
		if (order.getStatus().equals(YqOrder.STATUS_NOTPAY)) {
			if (new Date().getTime() <= order.getExpires().getTime()) {
				renderPay(order);
				return true;
			} else {
				order.closeOrder();
				LogKit.info("订单超时,重新下单");
			}
		} else {
			LogKit.info("非未支付订单");
		}
		return false;
	}

	public void directPay() {

	}

	/**
	 * 是否已能参团
	 * 
	 * @param product
	 * @return
	 */
	private boolean canJoinedGroup(YqProduct product, Long userId, Long groupId) {
		Long productId = product.getId();
		YqGroup joinedGroup = YqGroup.dao.findJoinedGroup(userId, productId);
		if (joinedGroup != null) {
			renderFailure("已加入团购");
			return false;
		}
		if (groupId != null) {
			// 添加团购成员
			YqUserOrderGroup userOrderGroup = YqUserOrderGroup.dao.findById(groupId, userId);
			if (userOrderGroup != null) {
				Long orderId = userOrderGroup.getOrderId();
				if (orderId != null) {
					YqOrder order = YqOrder.dao.findById(orderId);
					if (order != null) {
						if (order.getStatus().equals(YqOrder.STATUS_PAID)) {
							LogKit.warn("已支付团!! " + groupId + " " + userId + " " + productId);
							renderFailure("已支付团");
							return false;
						}
					}
				}
			}
			YqGroup group = YqGroup.dao.findById(groupId);
			if (group == null) {
				renderFailure("参团失败");
				return false;
			}
			group.updateGroupUserCount();
			if (group.getIsClosed().equals(1)) {
				renderFailure("已结束拼团");
				return false;
			}
			if (group.getIsDone().equals(1)) {
				renderFailure("拼团已完成");
				return false;
			}
			if (group.getExpire().getTime() <= new Date().getTime()) {
				renderFailure("拼团已超时");
				return false;
			}
		}
		return true;
	}

	/**
	 * 支付宝支付
	 */
	public void alipay() {
		renderSuccess();
	}

	/**
	 * 充值
	 */
	public void charge() {
		renderDevelop();
	}

	/**
	 * 通过orderId支付
	 * 
	 * @return
	 */
	private boolean isOrderPay(YqUser user) {
		Long payOrderId = getParaToLong("orderId");
		if (payOrderId == null) {
			return false;
		} else {
			YqOrder order = YqOrder.dao.findById(payOrderId);
			if (order == null) {
				renderError(404);
				return true;
			}
			if (!user.equals(order.getUserId())) {
				renderError(404);
				return true;
			}
			order.updateOrderStatus();
			if (canPay(order)) {
				return true;
			} else {
				renderFailure("订单已失效");
				return true;
			}
		}
	}

	/**
	 * 团购支付
	 */
	public void payGroup() {
		YqUser user = getUser();
		Long userId = user.getId();

		Long productGroupId = getParaToLong("productGroup");
		if (productGroupId == null) {
			LogKit.info("productGroupId null");
			renderError(404);
			return;
		}
		YqProductGroup productGroup = YqProductGroup.dao.findById(1);
		if (productGroup == null) {
			LogKit.info("productGroup null");
			renderError(404);
			return;
		}

		if (isOrderPay(user)) {
			return;
		}
		Long productId = productGroup.getProductId();
		Long groupId = getParaToLong("groupId");
		YqProduct product = YqProduct.dao.findById(productId);
		if (product == null) {
			LogKit.info("product null");
			renderError(404);
			return;
		}
		boolean isGroup = product.getIsGroup().equals(1);
		if (!isGroup) {
			renderFailure("not group");
			return;
		}
		String nationalCode = getPara("nationalCode", "");
		String telNumber = getPara("telNumber", "");
		String cityName = getPara("cityName", "");
		String postalCode = getPara("postalCode", "");
		String detailInfo = getPara("detailInfo", "");
		String provinceName = getPara("provinceName", "");
		String userName = getPara("userName", "");
		String countyName = getPara("countyName", "");
		int count = getParaToInt("count", 1);
		String size = getPara("size", "");
		String remark = getPara("remark", "");
		Long formatId = getParaToLong("formatId");
		String extraInfo = getPara("extraInfo");

		if (product.getStorage() < count) {
			LogKit.info("productId:" + product.getId() + " 库存不足 - storage:" + product.getStorage() + " count:" + count);
			renderFailure("库存不足");
			return;
		}

		if (isGroup) {
			if (!canJoinedGroup(product, userId, groupId)) {
				return;
			}
		}

		YqApp app = getApp();
		YqOrder order = new YqOrder(app);
		order.setOutTradeNo(YqOrder.genTradeNo());
		int totalFee = productGroup.getPrice() * 100 * count;

		order.setTotalFee(String.valueOf(totalFee));
		// order.setAppId(APP_ID);
		// order.setMchId(PARTNER);
		order.setBody(product.getTitle());
		String openid = user.getOpenId();
		order.setOpenid(openid);
		order.save();
		String outTradeNo = YqOrder.genTradeNo() + YqOrder.MIN_HASHID.encode(order.getId());
		order.setOutTradeNo(outTradeNo);
		order.update();
		Long shopId = product.getShopId();
		boolean pushFlag = order.pushOrder(IpKit.getRealIpV2(getRequest()), shopId);
		if (!pushFlag) {
			renderFailure("下单失败");
			return;
		}

		order.setUserId(userId);
		order.update();

		YqOrderInfo newOrderInfo = new YqOrderInfo();
		// newOrderInfo.setType(YqOrder.TYPE_PRODUCT);
		newOrderInfo.setName(userName);
		newOrderInfo.setMobile(telNumber);
		newOrderInfo.setAddress(provinceName + cityName + countyName + detailInfo);
		newOrderInfo.setCount(count);
		newOrderInfo.setPostalCode(postalCode);
		newOrderInfo.setNationalCode(nationalCode);
		newOrderInfo.setRemark(remark);
		newOrderInfo.setSize(size);
		newOrderInfo.setFormatId(formatId);
		newOrderInfo.setExtraInfo(extraInfo);

		if (isGroup) {
			if (!EN_MUTI_PAY_GROUP) {
				SqlPara paidGrpupPara = db.getSqlPara("YQPaidGroup", Kv.by("userId", userId));
				if (YqGroup.dao.findFirst(paidGrpupPara) != null) {
					renderFailure("请勿重复购买");
					return;
				}
			}
			if (groupId == null) {
				// YqGroup group = YqGroup.dao.findBy(userId, productId);
				// if (group != null) {
				// if (group.getIsDone().equals(1)) {
				// renderFailure("拼团已成功");
				// return;
				// }
				// if (group.getIsClosed().equals(1)) {
				// renderFailure("拼团已关闭");
				// return;
				// }
				// if (group.getExpire().getTime() <= new Date().getTime()) {
				// renderFailure("拼团已超时");
				// return;
				// }
				// }
				YqGroup group = null;
				// 如果没有团,生成团
				if (group == null) {
					group = new YqGroup();
					group.setUserId(userId);
					group.setProductId(productId);

					Date expire = new DateTime().plusHours(productGroup.getGroupHours()).toDate();
					group.setExpire(expire);
					group.setCount(productGroup.getGroupCount());
					group.save();
				}
				groupId = group.getId();
			}
			// 添加团购成员
			YqUserOrderGroup userOrderGroup = YqUserOrderGroup.dao.findById(groupId, userId);
			if (userOrderGroup == null) {
				userOrderGroup = new YqUserOrderGroup();
				userOrderGroup.setUserId(userId);
				userOrderGroup.setGroupId(groupId);
				userOrderGroup.setOrderId(order.getId());
				userOrderGroup.save();
			} else {
				userOrderGroup.setOrderId(order.getId());
				userOrderGroup.update();
			}
			order.setData("groupId:" + groupId);
			order.setType(YqOrder.TYPE_GROUP);

			newOrderInfo.setType(YqOrder.TYPE_GROUP);
			newOrderInfo.setGroupId(groupId);
			newOrderInfo.setIsGroup(1);
		} else {
			order.setData("productId:" + productId);
		}
		Long orderId = order.getId();
		newOrderInfo.setIsNeedTrack(product.getIsNeedTrack());
		newOrderInfo.setProductId(productId);
		newOrderInfo.setOrderId(orderId);
		newOrderInfo.setTitle(product.getTitle());
		newOrderInfo.setCover(product.getCover());
		newOrderInfo.setIntro("");
		newOrderInfo.setPrice(String.valueOf(productGroup.getPrice()));
		newOrderInfo.setUserId(userId);
		newOrderInfo.setRefId(productId);
		String code = HASHID.encode(orderId);
		newOrderInfo.setHashId(code);
		// String qrcodeImageUrl = "http://qr.liantu.com/api.php?text=" + code;
		String qrcodeImageUrl = "http://release.zhen-yee.com/api/qrcode?text=" + code;
		newOrderInfo.setQrcode(qrcodeImageUrl);
		newOrderInfo.setCardType(product.getCardType());
		if (product.getCardType().equals(1)) { // 次卡
			newOrderInfo.setUseLimit(product.getCardUseLimit());
			newOrderInfo.setIsCard(1);
		} else if (product.getCardType().equals(2)) { // 日卡
			newOrderInfo.setCardAvailableDay(product.getCardAvailableDay());
			newOrderInfo.setIsCard(1);
		} else if (product.getCardType().equals(3)) { // 过期卡
			newOrderInfo.setCardExpire(product.getCardExpire());
			newOrderInfo.setIsCard(1);
		}
		newOrderInfo.save();
		order.update();
		product.setStorage(product.getStorage() - count);
		product.update();
		renderPay(order);

	}

	private YqOrderInfo genOrderInfo() {
		String nationalCode = getPara("nationalCode", "");
		String telNumber = getPara("telNumber", "");
		String cityName = getPara("cityName", "");
		String postalCode = getPara("postalCode", "");
		String detailInfo = getPara("detailInfo", "");
		String provinceName = getPara("provinceName", "");
		String userName = getPara("userName", "");
		String countyName = getPara("countyName", "");
		int count = getParaToInt("count", 1);
		String size = getPara("size", "");
		String remark = getPara("remark", "");
		Long formatId = getParaToLong("formatId");
		String extraInfo = getPara("extraInfo");
		YqOrderInfo newOrderInfo = new YqOrderInfo();
		// newOrderInfo.setType(YqOrder.TYPE_PRODUCT);
		newOrderInfo.setName(userName);
		newOrderInfo.setMobile(telNumber);
		newOrderInfo.setAddress(provinceName + cityName + countyName + detailInfo);
		newOrderInfo.setCount(count);
		newOrderInfo.setPostalCode(postalCode);
		newOrderInfo.setNationalCode(nationalCode);
		newOrderInfo.setRemark(remark);
		newOrderInfo.setSize(size);
		newOrderInfo.setFormatId(formatId);
		newOrderInfo.setExtraInfo(extraInfo);
		return newOrderInfo;
	}

	/**
	 * 支付
	 */
	public void pay() {
		boolean shouldRealPay = true;
		YqUser user = getUser();
		if (user == null) {
			renderError(401);
			return;
		}
		Long userId = user.getId();
		if (isOrderPay(user)) {
			return;
		}
		Long productId = getParaToLong("productId");
		Long itemId = getParaToLong("itemId");
		Long groupId = getParaToLong("groupId");
		if (itemId != null) {
			YqItem item = YqItem.dao.findById(itemId);
			if (item == null) {
				renderError(404);
				LogKit.info("item null");
				return;
			}
			productId = item.getProductId();
		}
		if (productId == null) {
			LogKit.info("productId null");
			renderError(404);
			return;
		}
		YqProduct product = YqProduct.dao.findById(productId);
		if (product == null) {
			LogKit.info("product null");
			renderError(404);
			return;
		}
		String nationalCode = getPara("nationalCode", "");
		String telNumber = getPara("telNumber", "");
		String cityName = getPara("cityName", "");
		String postalCode = getPara("postalCode", "");
		String detailInfo = getPara("detailInfo", "");
		String provinceName = getPara("provinceName", "");
		String userName = getPara("userName", "");
		String countyName = getPara("countyName", "");
		int count = getParaToInt("count", 1);
		String size = getPara("size", "");
		String remark = getPara("remark", "");
		Long formatId = getParaToLong("formatId");
		String extraInfo = getPara("extraInfo");
		String information = getPara("information");

		if (product.getStorage() < count) {
			LogKit.info("productId:" + product.getId() + " 库存不足 - storage:" + product.getStorage() + " count:" + count);
			renderFailure("库存不足");
			return;
		}

		boolean isGroup = product.getIsGroup().equals(1);
		if (isGroup) {
			if (!canJoinedGroup(product, userId, groupId)) {
				return;
			}
		}
		// int type = isGroup ? YqOrder.TYPE_GROUP : YqOrder.TYPE_PRODUCT;
		if (EN_REPAY_PRODUCT) {
			Kv kv = Kv.create();
			kv.set("userId", userId);
			// kv.set("type", type);
			kv.set("productId", productId);
			SqlPara sqlPara = db.getSqlPara("YQFindExistOrder", kv);
			YqOrderInfo orderInfo = YqOrderInfo.dao.findFirst(sqlPara);
			if (orderInfo != null) {
				YqOrder order = YqOrder.dao.findById(orderInfo.getOrderId());
				order.updateOrderStatus();
				if (canPay(order)) {
					return;
				}
			} else {
				LogKit.info("不存要支付的订单");
			}
		}

		YqApp app = getApp();
		// app = YqApp.dao.findById(2);
		app.print();
		YqOrder order = new YqOrder(app);
		order.setOutTradeNo(YqOrder.genTradeNo());
		Float totalFee = product.getPrice() * 100 * count;
		if (!isGroup) {
			// if (StrKit.notBlank(product.getSizes()) && StrKit.notBlank(size))
			// {
			// JSONArray sizes = JSONUtil.parseArray(product.getSizes());
			// for (int i = 0; i < sizes.size(); i++) {
			// JSONObject obj = sizes.getJSONObject(i);
			// if (size.equals(obj.getStr("size"))) {
			// totalFee = obj.getFloat("price") * 100 * count;
			// }
			// }
			// }
			SqlPara spFormat = db.getSqlPara("YQAdminProductFormat", Kv.by("productId", productId));
			List<YqProductFormat> formats = YqProductFormat.dao.find(spFormat);
			for (YqProductFormat format : formats) {
				// if (size.equals(format.getTitle())) {
				// totalFee = format.getFee().floatValue() * count;
				// }
				if (formatId.equals(format.getId())) {
					if (format.getStorage() < count) {
						LogKit.info("productId:" + product.getId() + " 库存不足 - formatId:" + format.getId() + " storage:"
								+ format.getStorage() + " count:" + count);
						renderFailure("选择的规格库存不足");
						return;
					}
					// TODO 减format库存
					totalFee = format.getFee().floatValue() * count;
					break;
				}
			}
		}
		int totalFeeInt = totalFee.intValue();
		order.setTotalFee(String.valueOf(totalFeeInt));

		// order.setAppId(APP_ID);
		// order.setMchId(PARTNER);

		order.setBody(product.getTitle());
		String openid = user.getOpenId();
		order.setOpenid(openid);
		order.setShopId(product.getShopId());
		order.save();
		String outTradeNo = YqOrder.genTradeNo() + YqOrder.MIN_HASHID.encode(order.getId());
		order.setOutTradeNo(outTradeNo);
		order.update();
		// Integer extraBanalce = user.getExtraBanalce();
		// Integer toPay = totalFeeInt - extraBanalce;
		// if (toPay < 0) {
		// user.setExtraBanalce(extraBanalce - totalFeeInt);
		// user.update();
		// shouldRealPay = false;
		// order.setStatus(1);
		// } else {
		// order.setTotalFee(String.valueOf(totalFeeInt - extraBanalce));
		// boolean pushFlag = order.pushOrder(IpKit.getRealIpV2(getRequest()));
		// if (!pushFlag) {
		// renderFailure("下单失败");
		// return;
		// }
		// }
		boolean pushFlag = order.pushOrder(IpKit.getRealIpV2(getRequest()));
		if (!pushFlag) {
			renderFailure("下单失败");
			return;
		}
		order.setUserId(userId);
		order.update();

		YqOrderInfo newOrderInfo = genOrderInfo();

		if (isGroup) {
			if (!EN_MUTI_PAY_GROUP) {
				SqlPara paidGrpupPara = db.getSqlPara("YQPaidGroup", Kv.by("userId", userId));
				if (YqGroup.dao.findFirst(paidGrpupPara) != null) {
					renderFailure("请勿重复购买");
					return;
				}
			}
			if (groupId == null) {
				// YqGroup group = YqGroup.dao.findBy(userId, productId);
				// if (group != null) {
				// if (group.getIsDone().equals(1)) {
				// renderFailure("拼团已成功");
				// return;
				// }
				// if (group.getIsClosed().equals(1)) {
				// renderFailure("拼团已关闭");
				// return;
				// }
				// if (group.getExpire().getTime() <= new Date().getTime()) {
				// renderFailure("拼团已超时");
				// return;
				// }
				// }
				YqGroup group = null;
				// 如果没有团,生成团
				if (group == null) {
					group = new YqGroup();
					group.setUserId(userId);
					group.setProductId(productId);

					Date expire = new DateTime().plusHours(product.getGroupHours()).toDate();
					group.setExpire(expire);
					group.setCount(product.getGroupCount());
					group.save();
				}
				groupId = group.getId();
			}
			// 添加团购成员
			YqUserOrderGroup userOrderGroup = YqUserOrderGroup.dao.findById(groupId, userId);
			if (userOrderGroup == null) {
				userOrderGroup = new YqUserOrderGroup();
				userOrderGroup.setUserId(userId);
				userOrderGroup.setGroupId(groupId);
				userOrderGroup.setOrderId(order.getId());
				userOrderGroup.save();
			} else {
				userOrderGroup.setOrderId(order.getId());
				userOrderGroup.update();
			}
			order.setData("groupId:" + groupId);
			order.setType(YqOrder.TYPE_GROUP);

			newOrderInfo.setType(YqOrder.TYPE_GROUP);
			newOrderInfo.setGroupId(groupId);
			newOrderInfo.setIsGroup(1);
		} else {
			order.setData("productId:" + productId);
		}
		Long orderId = order.getId();
		newOrderInfo.setIsNeedTrack(product.getIsNeedTrack());
		newOrderInfo.setProductId(productId);
		newOrderInfo.setOrderId(orderId);
		newOrderInfo.setTitle(product.getTitle());
		newOrderInfo.setCover(product.getCover());
		newOrderInfo.setIntro("");
		newOrderInfo.setPrice(String.valueOf(product.getPrice()));
		newOrderInfo.setUserId(userId);
		newOrderInfo.setRefId(productId);
		String code = HASHID.encode(orderId);
		newOrderInfo.setHashId(code);
		newOrderInfo.setItemId(itemId);
		// String qrcodeImageUrl = "http://qr.liantu.com/api.php?text=" + code;
		String qrcodeImageUrl = "http://release.zhen-yee.com/api/qrcode?text=" + code;
		newOrderInfo.setQrcode(qrcodeImageUrl);
		newOrderInfo.setCardType(product.getCardType());
		if (product.getCardType().equals(1)) { // 次卡
			newOrderInfo.setUseLimit(product.getCardUseLimit());
			newOrderInfo.setIsCard(1);
		} else if (product.getCardType().equals(2)) { // 日卡
			newOrderInfo.setCardAvailableDay(product.getCardAvailableDay());
			newOrderInfo.setIsCard(1);
		} else if (product.getCardType().equals(3)) { // 过期卡
			newOrderInfo.setCardExpire(product.getCardExpire());
			newOrderInfo.setIsCard(1);
		}
		newOrderInfo.setExtraInfo(extraInfo);
		newOrderInfo.setInformation(information);
		newOrderInfo.save();

		order.update();

		cache.setex("YQ_" + order.getOutTradeNo(), 7200, count);
		// product.setStorage(product.getStorage() - count);
		product.update();

		if (shouldRealPay) {
			renderPay(order);
		} else {
			new OrderHandler().onSuccess(order);
			renderSuccess("支付成功");
		}

		// renderSuccess();
	}

	/**
	 * 购物车结算
	 * 
	 * @Time 2019年3月4日 下午10:45:43
	 */
	@Before({ YQUserInterceptor.class, Tx.class })
	public void payCart() {
		renderMsg("提示");
		String cart = getPara("cart");
		String extraInfo = getPara("extraInfo");
		String information = getPara("information");
		if (StrKit.isBlank(cart)) {
			renderFailure("下单失败 500101");
			return;
		}
		YqUser user = getUser();
		Long userId = user.getId();
		boolean flag = db.tx(new IAtom() {

			@Override
			public boolean run() throws SQLException {
				boolean shouldRealPay = true;
				try {
					ArrayList<DBMap> arrayList = new ArrayList<>();
					Integer total = 0;
					// String[] cartIds = cartStr.split(";");
					JSONArray array = JSONUtil.parseArray(cart);
					for (Object object : array) {
						JSONObject info = new JSONObject(object);
						// System.out.println(info.getLong("productId"));
						Long productId = info.getLong("productId");
						Long formatId = info.getLong("formatId");
						Integer count = info.getInt("count");
						if (productId == null) {
							renderFailure("下单失败  productId ==null");
							return false;
						}
						if (formatId == null) {
							renderFailure("下单失败  formatId ==null");
							return false;
						}
						if (count == null) {
							renderFailure("下单失败  count ==null");
							return false;
						}

						YqProductFormat productFormat = YqProductFormat.dao.findById(formatId);
						if (productFormat == null) {
							renderFailure("下单失败  productFormat ==null");
							return false;
						}
						if (productFormat.getFlag().equals(1)) {
							renderFailure("下单失败 已选规格已失效");
							return false;
						}
						if (!productFormat.getProductId().equals(productId)) {
							renderFailure("下单失败 500104");
							return false;
						}
						if (productFormat.getStorage() - count < 0) {
							renderFailure("下单失败 500105");
							return false;
						}
						YqProduct product = YqProduct.dao.findById(productId);
						if (product.getIsGroup().equals(1)) {
							renderMsg("团购商品无法结算");
							return false;
						}
						total += count * productFormat.getFee();
						DBMap map = new DBMap();
						map.put("title", product.getTitle());
						map.put("productId", product.getId());
						map.put("fee", productFormat.getFee());
						map.put("count", count);
						map.put("cover", product.getCover());
						map.put("format", productFormat.getTitle());
						map.put("formatId", productFormat.getId());
						arrayList.add(map);
						YqCart cart = YqCart.dao.findById(formatId, productId, userId);
						if (cart == null) {
							// renderFailure("下单失败 cart ==null");
							// return false;
							continue;
						}
						if (!cart.delete()) {
							renderFailure("下单失败  delete");
							return false;
						}
					}
					YqApp app = getApp();
					// YqApp app = YqApp.dao.findById(2);

					/**
					 * 加上快递费
					 */
					int expressCost = app.getExpressCost() * 100;
					int expressFeeLimit = app.getExpressFeeLimit() * 100;
					// int expressLimit = app.getExpressLimit() * 100;
					if (expressFeeLimit >= total) {
						total += expressCost;
					}

					YqOrder order = new YqOrder(app);
					order.setTotalFee(String.valueOf(total));

					// order.setAppId(APP_ID);
					// order.setMchId(PARTNER);

					order.setBody("支付商品");
					String openid = user.getOpenId();
					order.setOpenid(openid);
					order.setUserId(userId);
					order.save();
					String outTradeNo = YqOrder.genTradeNo() + YqOrder.MIN_HASHID.encode(order.getId());
					order.setOutTradeNo(outTradeNo);
					order.update();

					// Integer extraBanalce = user.getExtraBanalce();
					// Integer toPay = total - extraBanalce;
					// if (toPay < 0) {
					// user.setExtraBanalce(extraBanalce - total);
					// user.update();
					// shouldRealPay = false;
					// order.setStatus(1);
					// } else {
					// order.setTotalFee(String.valueOf(total - extraBanalce));
					// boolean pushFlag =
					// order.pushOrder(IpKit.getRealIpV2(getRequest()));
					// if (!pushFlag) {
					// renderFailure("下单失败");
					// return false;
					// }
					//
					// }
					boolean pushFlag = order.pushOrder(IpKit.getRealIpV2(getRequest()));
					if (!pushFlag) {
						renderFailure("下单失败");
						return false;
					}
					order.update();

					Long orderId = order.getId();
					if (DEBUG) {
						LogKit.info("orderId: " + orderId);
					}

					YqOrderCart orderCart = new YqOrderCart();
					orderCart.setOrderId(orderId);
					orderCart.setContent(JsonKit.toJson(arrayList));
					orderCart.save();

					YqOrderInfo newOrderInfo = genOrderInfo();
					newOrderInfo.setOrderId(orderId);
					newOrderInfo.setUserId(userId);
					newOrderInfo.setExtraInfo(extraInfo);
					newOrderInfo.setInformation(information);
					newOrderInfo.save();

					// for (String string : cartIds) {
					// Long cartId = Long.parseLong(string);
					// YqCart cart = YqCart.dao.findById(cartId);
					// if (cart == null) {
					// renderFailure("下单失败 500102");
					// return false;
					// }
					// if (!user.getId().equals(cart.getUserId())) {
					// renderFailure("下单失败 500103");
					// return false;
					// }

					// int count = cart.getCount();

					String prepay_id = order.getPrepayId();
					if (shouldRealPay) {
						renderPay(order);
					} else {
						new OrderHandler().onSuccess(order);
						renderSuccess("支付成功");
					}
					return true;
				} catch (Exception e) {
					LogKit.error("下单失败 500107", e);
					renderFailure("下单失败 500107");
					return false;
				}
			}
		});
		// if (flag) {
		// renderSuccess();
		// }
	}
}
